import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.Socket;
import java.util.*;

public class AdminSystem {
    private Socket socket;
    private Monitor monitor;
    private Administrator admin;
    private final Scanner SC = ClientScanner.sc;
    private List<ChoiceQuestion> choiceQuestions;
    private List<TrueOrFalseQuestion> trueOrFalseQuestions;

    public AdminSystem(Socket socket, Monitor monitor, Administrator admin, List<?>[] allQuestions) {
        this.socket = socket;
        this.monitor = monitor;
        this.admin = admin;
        choiceQuestions = MyTool.castList(allQuestions[0], ChoiceQuestion.class);
        trueOrFalseQuestions = MyTool.castList(allQuestions[1], TrueOrFalseQuestion.class);
    }

    public void launch() {
        String input;
        do {
            Displayer.printAdminFrame(admin.getName());
            input = inputJudge("[012]");
            switch (input) {
                case "0":return;
                case "1":
                    studentManageModule();
                    break;
                case "2":
                    questionManageModule();
                    break;
            }
        } while (!input.matches("0"));
    }

    private String inputJudge( String regex) {
        return ClientScanner.inputJudge(regex);
    }

    private void studentManageModule() {
        String input;
        do {
            Displayer.printStudentManageModuleFrame();
            input =  inputJudge("[01234]");
            switch (input) {
                case "0":return;
                case "1":{
                    System.out.println("注意: 此操作添加学员信息为强制添加, " +
                            "如果用户名与已经存在的用户相同, " +
                            "会覆盖已有的相同用户名的学员信息");
                    System.out.println("提示: 此操作添加的学员的密码和昵称与用户名相同");
                    System.out.println("输入要增加的用户名\n" +
                            "输入多个时以1个空格隔开，输入'0'返回上一界面");
                    String userNames = inputJudge("[\\w]+( [\\w]+)*");
                    if (userNames.equals("0")) {
                        break;
                    }
                    String[] userNameArr = userNames.split(" ");
                    List<Student> studentList = new ArrayList<>();
                    for (String item : userNameArr) {
                        studentList.add(new Student(item, item, item));
                    }
                    synchronized (monitor.addUserLock) {
                        new ClientSendThread(socket, new Message("forceAddStudent",
                                new MultiStudent(studentList))).start();
                        try {
                            monitor.addUserLock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    int[] addResult = monitor.getAddUserResult();
                    System.out.println("增加了"+addResult[0]+"个用户, 覆盖了"+addResult[1]+"个用户");
                    if (addResult[2] !=0 ) {
                        System.out.println("检测到"+addResult[2]+"个你无权覆盖的用户");
                    }
                    break;
                }
                case "2":{
                    System.out.println("注意: 此操作将直接删除用户, 删除后无法恢复旧信息");
                    System.out.println("输入要删除的用户名\n" +
                            "输入多个时以1个空格隔开，输入'0'返回上一界面");
                    String userNames = inputJudge("[\\w]+( [\\w]+)*");
                    if (userNames.equals("0")) {
                        break;
                    }
                    String[] userNameArr = userNames.split(" ");
                    synchronized (monitor.deleteUserLock) {
                        new ClientSendThread(socket, new Message("deleteUser",
                                new ConveyableObject(userNameArr))).start();
                        try {
                            monitor.deleteUserLock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    int[] deleteResult = monitor.getDeleteUserResult();
                    System.out.println("删除了"+deleteResult[0]+"个用户, "+deleteResult[1]+"个用户未找到");
                    if (deleteResult[2] !=0 ) {
                        System.out.println("检测到"+deleteResult[2]+"个你无权删除的用户");
                    }
                    break;
                }
                case "3":{
                    System.out.println("未完善....");
                    break;
                }
                case "4":{
                    System.out.println("未完善...");
                    break;
                }
            }
        } while (!input.matches("0"));
    }
    private void questionManageModule() {
        Displayer.printQuestionManageModuleFrame();
        String input = inputJudge("[012345]");
        switch (input) {
            case "0": {break;}
            case "1": {
                System.out.println("增加一道:1选择题2判断题?(1/2/0返回)");
                String tInput = inputJudge("[012]");
                if (tInput.equals("0")) {
                    break;
                }
                if (tInput.equals("1")) {
                    String[] choiceQuestionInfo = getChoiceQuestionInfo();
                    ChoiceQuestion[] cQ = new ChoiceQuestion[]{new ChoiceQuestion(choiceQuestionInfo)};
                    addChoiceQ(cQ);
                }else {
                    String[] trueOrFalseQuestionInfo = getTrueOrFalseQuestionInfo();
                    TrueOrFalseQuestion[] tofQ = new TrueOrFalseQuestion[]{new TrueOrFalseQuestion(trueOrFalseQuestionInfo)};
                    addTrueOrFalseQ(tofQ);
                }
                System.out.println("增加成功");
                break;
            }
            case "2": {
                System.out.println("要删除:1.选择题2.判断题?(1/2/0返回)");
                String tInput = inputJudge("[012]");
                if (tInput.equals("0")) {
                    break;
                }

                switch (tInput) {
                    case "1":
                        Displayer.printAllChoiceQuestions(choiceQuestions);
                        break;
                    case "2":
                        Displayer.printAllTrueOrFalseQuestions(trueOrFalseQuestions);
                        break;
                }
                System.out.println("请输入要删除的题号(输入'0'返回)");
                String tIndex = inputJudge("0|[\\d]+( [\\d]+)*");
                if (tIndex.equals("0")) {
                    break;
                }
                String[] questionIDStrArr = tIndex.split(" ");
                int[] questionIDArr = new int[questionIDStrArr.length];
                for (int i = 0;i<questionIDArr.length;i++) {
                    questionIDArr[i] = Integer.parseInt(questionIDStrArr[i]);
                }
                List<Integer> questionIDList = new ArrayList<>();
                for (int item : questionIDArr) {
                    questionIDList.add(item);
                }
                Collections.sort(questionIDList);
                if (tInput.equals("1")){
                    synchronized (monitor.deleteQuestionLock) {
                        new ClientSendThread(socket, new Message("deleteChoiceQuestion",
                                new ConveyableObject(questionIDList))).start();
                        try {
                            monitor.deleteQuestionLock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }else {
                    synchronized (monitor.deleteQuestionLock) {
                        new ClientSendThread(socket, new Message("deleteTrueOrFalseQuestion",
                                new ConveyableObject(questionIDList))).start();
                        try {
                            monitor.deleteQuestionLock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                int[] result = monitor.getDeleteQuestionResult();
                System.out.println("删除了"+result[0]+"道题目");
                break;
            }
            case "3": {
                System.out.println("该功能完善中...");
                break;
            }
            case "4": {
                Displayer.printAllChoiceQuestions(choiceQuestions);
                Displayer.printAllTrueOrFalseQuestions(trueOrFalseQuestions);
                System.out.println("输入'0'返回");
                inputJudge("0");
                break;
            }
            case "5": {
                System.out.println("输入存有题目的txt文件路径:");
                String path = SC.nextLine();
                try {
                    inputFromTXT(new File(path));
                    System.out.println("导入成功");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private String[] getTrueOrFalseQuestionInfo() {
        System.out.println("提示：输入题目信息时系统不做过多的判断，请小心输入！");
        String[] info = new String[TrueOrFalseQuestion.LINE_NUMBER];
        System.out.println("请输入题干");
        info[0] = SC.nextLine();
        System.out.println("请输入答案(true/false)");
        info[1] = inputJudge("true|false");
        return info;
    }

    private String[] getChoiceQuestionInfo() {
        System.out.println("提示：输入题目信息时系统不做过多的判断，请小心输入！");
        String[] info = new String[ChoiceQuestion.LINE_NUMBER];
        System.out.println("请输入题干");
        info[0] = SC.nextLine();
        System.out.println("请输入选项A");
        info[1] = SC.nextLine();
        System.out.println("请输入选项B");
        info[2] = SC.nextLine();
        System.out.println("请输入选项C");
        info[3] = SC.nextLine();
        System.out.println("请输入选项D");
        info[4] = SC.nextLine();
        System.out.println("请输入答案(A/B/C/D)");
        info[5] = inputJudge("[ABCD]|[abcd]");
        return info;
    }

    private void addTrueOrFalseQ(TrueOrFalseQuestion[] questions) {
        ConveyableObject object = new ConveyableObject(questions);
        synchronized (monitor.addQuestionLock) {
            new ClientSendThread(socket, new Message("addTrueOrFalseQ", object)).start();
            try {
                monitor.addQuestionLock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void addChoiceQ(ChoiceQuestion[] questions) {
        ConveyableObject object = new ConveyableObject(questions);
        synchronized (monitor.addQuestionLock) {
            new ClientSendThread(socket, new Message("addChoiceQ", object)).start();
            try {
                monitor.addQuestionLock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void inputFromTXT(File txt) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(txt));
        String read;
        List<ChoiceQuestion> list1 = new ArrayList<>();
        List<TrueOrFalseQuestion> list2 = new ArrayList<>();
        do {
            System.out.println(111);
            read = br.readLine();
            if (read != null) {
                if (read.equals("trueOrFalseQuestion")) {
                    String[] vars = new String[TrueOrFalseQuestion.LINE_NUMBER];
                    for (int i = 0; i < TrueOrFalseQuestion.LINE_NUMBER; i++) {
                        vars[i] = br.readLine().split(" ")[1];
                    }
                    TrueOrFalseQuestion trueOrFalseQuestion = new TrueOrFalseQuestion(vars);
                    System.out.println(trueOrFalseQuestion);
                    list2.add(trueOrFalseQuestion);

                }
                else if (read.equals("choiceQuestion")) {
                    String[] vars = new String[ChoiceQuestion.LINE_NUMBER];
                    for (int i = 0; i < ChoiceQuestion.LINE_NUMBER; i++) {
                        vars[i] = br.readLine().split(" ")[1];
                    }
                    ChoiceQuestion choiceQuestion = new ChoiceQuestion(vars);
                    System.out.println(choiceQuestion);
                    list1.add(choiceQuestion);
                }
            }
        }while (read != null);

        ChoiceQuestion[] choiceQuestions = list1.toArray(new ChoiceQuestion[0]);
        TrueOrFalseQuestion[] trueOrFalseQuestions = list2.toArray(new TrueOrFalseQuestion[0]);
        synchronized (monitor.addQuestionLock) {
            addChoiceQ(choiceQuestions);
            addTrueOrFalseQ(trueOrFalseQuestions);
        }
    }


}
